<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('核销时间')">
              <j-date
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('商品名称')">
              <a-input :placeholder="$t('请输入商品名称')" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a-button
                type="primary"
                icon="download" :loading="exloading"
                style="margin-left: 8px"
                @click="handleExportXls($t('团购核销汇总'))"
                v-has="'ThirdReport:export'"
                >{{ $t('导出') }}</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        class="printable-table"
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSources"
        :pagination="false"
        :loading="false"
        :customHeaderRow="customHeaderRow"
        :customRow="customRow"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">{{
            $t('下载')
          }}</a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">{{ $t('详情') }}</a>
        </span>
        <!-- 自定义 goodsForm 列渲染 -->
        <template slot="goodsFormCell" slot-scope="text, record">
          <template v-if="record.showGroupColumn">
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: 'GroupVerificationSummary',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      moment,
      description: '团购核销汇总页面',
      // 表头
      groupColumn: 'channel',
      columns: [
        {
          title: this.$t('核销平台'),
          align: 'center',
          dataIndex: this.groupColumn,
          width: 120,
          scopedSlots: { customRender: 'goodsFormCell' },
          customRender: this.groupColumnRender,
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('业务笔数'),
          align: 'center',
          dataIndex: 'bizNum',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'count',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('销售金额'),
          align: 'center',
          dataIndex: 'salePrice',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, record) => {
            if(!text){
              return '0.00'
            }
            return text.toFixed(2)
          },
        },
        {
          title: this.$t('币值'),
          align: 'center',
          dataIndex: 'coinValue',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, record) => {
            if(!text){
              return '0.00'
            }
            return text.toFixed(2)
          },
        }
      ],
      url: {
        list: '/report/third/thirdReport/list',
        exportXlsUrl: '/report/third/thirdReport/exportXls',
      },
      queryParam: {
        createTime_begin:moment().format('YYYY-MM-DD 00:00:00'),
        createTime_end:moment().format('YYYY-MM-DD 23:59:59'),
      },
      isCustom: true,
      isHideData: false,
      thRows: 1,
      isOptArea: true
    }
  },
  computed: {
    // 处理数据，按 goodsForm 分组并添加合计行
    dataSources() {
      // 1. 排除合计行
      let list = [ ...this.dataSource ]
      const filteredData = this.dataSource.filter((item, i) => i != this.dataSource.length - 1 )

      // 2. 按当前分组列分组
      const groups = {}
      filteredData.forEach((item) => {
        const groupKey = item[this.groupColumn]
        if (!groups[groupKey]) {
          groups[groupKey] = []
        }
        groups[groupKey].push(item)
      })
      // 3. 构建表格数据
      const result = []
      Object.keys(groups).forEach((groupValue) => {
        const items = groups[groupValue]
        // 添加分组数据
        items.forEach((item, index) => {
          if(index < items.length -1){
            result.push({
              ...item,
              showGroupColumn: index === 0, // 只有第一行显示channel
              rowSpan: items.length, //是为了包含小计行
              isSubTotal: false,
            })
          }
        })

        // 添加小计行
        result.push({
          [this.groupColumn]: groupValue,
          ...items[items.length - 1],
          showGroupColumn: items.length == 1?true:false,
          rowSpan: items.length == 1?1:0,
          isSubTotal: items.length == 1?false:true,
        })
      })

      // 4. 添加总计行
      const totalRow = list.find((item, i) => i === list.length-1 )
      if (totalRow) {
        result.push({
          ...totalRow,
          [this.groupColumn]: '合计',
          name: '',
          showGroupColumn: true,
          rowSpan: 1,
          isTotal: true,
        })
      }
      console.log(result)
      return result
    },
  },
  methods: {
    // 动态分组列渲染
    groupColumnRender(text, record) {
      return {
        children: record[this.groupColumn] ? record[this.groupColumn] : this.$t('合计'),
        attrs: {
          rowSpan: record.showGroupColumn ? record.rowSpan : 0,
        },
      }
    },
    initDictConfig() {
      this.searchQuery()
    },
    searchQuery() {
      this.selectedRowIndex = []
      this.loadData()
    },
    searchReset() {
      let that = this
      that.queryParam = {
        createTime_begin:moment().format('YYYY-MM-DD 00:00:00'),
        createTime_end:moment().format('YYYY-MM-DD 23:59:59'),
      }
      that.searchQuery()
    },
    customRow(r, i) {
      return {
        on: {
          click: () => {
            let x = this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i})
            if( x == -1 ){
              this.selectedRowIndex.push('a'+this.ipagination.current+''+i)
            }else{
              this.selectedRowIndex.splice(x, 1)
            }
          }
        },
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
          backgroundColor: this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i}) > -1 ? '#FFECE6' : '',
          fontWeight: r.channel == this.$t('合计') || r.name == this.$t('小计') ? 700 : 400,
        },
      }
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
@media print {
  @page {
    size: auto;
    margin: auto 3mm;
  }
  .printable-table {
    height: auto !important;
  }
  .printable-table .ant-table-body {
    height: auto !important;
    overflow: visible !important;
    max-height: none !important;
  }
  .printable-table .ant-table-container {
    height: auto !important;
  }
}
</style>